package com.cyan.app.workflow.activity.WHM;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cyan.app.workflow.R;
import com.cyan.app.workflow.base.activity.BaseActivity;
import com.cyan.app.workflow.bean.BaseBean;
import com.cyan.app.workflow.bean.InvbalBean;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.customview.PullDownView;
import com.cyan.app.workflow.customview.ShowTipDialog;
import com.cyan.app.workflow.util.AppUtils;
import com.cyan.app.workflow.util.network.GetRequestParams;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by DXW on 2016-04-06.
 */
public class GdllLlInvbatActivity extends BaseActivity {

    public static final String TAG = "GdllLlInvbatActivity";
    private InvbalBean invbalBean;
    private List<InvbalBean.InvbatBean> invbatBeans;
    private GdllLlInvbatAdapter adapter;
    private ListView prossinfo_lv;
    private PullDownView mPullDownView;
    private ShowTipDialog showdialog = new ShowTipDialog();
    private String mUnmsr1 = "";
    private String mUnmsr2 = "";
    private String mWareh = "";
    private String mItnbr = "";
    private Double mAppnum=0.00d;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.whm_gdll_ll_invbat);
        initView();
        titleBar();
        mPullDownView = (PullDownView) findViewById(R.id.whm_gdll_ll_invbat_lv);
        prossinfo_lv = mPullDownView.getListView();
        // 隐藏并且禁用头部刷新
        mPullDownView.setHideHeader();
        mPullDownView.setHideFooter();

        AsyncLoader task = new AsyncLoader();
        task.execute("303",mWareh,mItnbr);

    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }
    public class AsyncLoader extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            showdialog.showDialog(GdllLlInvbatActivity.this);
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            try{
                JSONObject param = new JSONObject();
                param.put("Wareh",params[1]);
                param.put("Itnbr",params[2]);
                result= GetRequestParams.getRequestResult(HttpConfig.HTTP_MAIN_SERVER_URL, params[0], param.toString(), getApplicationContext());
            }catch (Exception e){
                Log.e("error", e.toString());
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null) {
                showdialog.closeDialog();
                return;
            }
            InvbalCommonBean commonBean = new Gson().fromJson(s, InvbalCommonBean.class);
            if (commonBean.getCode() < 1) {
                AppUtils.showTip(GdllLlInvbatActivity.this, commonBean.getMsg());
            } else {
                invbalBean = commonBean.getResult();
                adapter = new GdllLlInvbatAdapter(GdllLlInvbatActivity.this);
                prossinfo_lv.setAdapter(adapter);
            }
            showdialog.closeDialog();
        }
    }
    private void titleBar() {
        TextView mTextView = (TextView) findViewById(R.id.top_title_info);
        mTextView.setText("申请数 - " + mAppnum);
        Button back = (Button) findViewById(R.id.top_title_back);
        back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回按钮
                finish();
            }
        });
        Button mButton = (Button)findViewById(R.id.top_title_refres_with_icon);
        mButton.setVisibility(View.VISIBLE);
        mButton.setText("确定");
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selected = 0;
                Double risqty = 0.00d;
                Double risqty2 = 0.00d;
                for (int i = 1; i < prossinfo_lv.getCount() - 1; i++) {
                    View view = prossinfo_lv.getChildAt(i);
                    CheckBox ss = (CheckBox) view.findViewById(R.id.whm_gdll_ll_invbat_list_c1);
                    if (!ss.isChecked()) {
                        //manpahdBeans.remove(i-1);
                        continue;
                    }
                    selected++;
                    EditText et = (EditText) view.findViewById(R.id.whm_gdll_ll_invbat_list_c4);
                    Double num =et.getText().toString().isEmpty()?0.00d:Double.parseDouble(et.getText().toString());
                    if (num > invbalBean.getInvbats().get(i - 1).getOnhand1()) {
                        AppUtils.showTip(GdllLlInvbatActivity.this, "发料数量不能大于库存数量");
                        return;
                    }
                    invbalBean.getInvbats().get(i - 1).setOnhand1(num);
                    risqty = risqty + num;

                    EditText et2 = (EditText) view.findViewById(R.id.whm_gdll_ll_invbat_list_c5);
                    Double num2 =et2.getText().toString().isEmpty()?0.00d:Double.parseDouble(et2.getText().toString());
                    if (num2 > invbalBean.getInvbats().get(i - 1).getOnhand2()) {
                        AppUtils.showTip(GdllLlInvbatActivity.this, "发料数量不能大于库存数量");
                        return;
                    }
                    invbalBean.getInvbats().get(i - 1).setOnhand2(num2);
                    risqty2 = risqty2 + num2;
                }

                if (selected == 0||risqty==0) {
                    AppUtils.showTip(GdllLlInvbatActivity.this, "请选择库位和输入发料数量");
                }else if(mAppnum + 0.99d < risqty){
                    AppUtils.showTip(GdllLlInvbatActivity.this, "发料数量不能大于申请数量");
                } else{
                    for (int i = prossinfo_lv.getCount()-1; i > 0 ; i--) {
                        View view = prossinfo_lv.getChildAt(i);
                        CheckBox ss = (CheckBox) view.findViewById(R.id.whm_gdll_ll_invbat_list_c1);
                        if (ss!=null&&!ss.isChecked()) {
                            invbalBean.getInvbats().remove(i-1);
                        }
                    }

                    risqty =new BigDecimal(risqty).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                    risqty2 =new BigDecimal(risqty2).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                    invbalBean.setOnhand1(risqty);
                    invbalBean.setOnhand2(risqty2);
                    Intent intent = new Intent();
                    Bundle bundle=new Bundle();
                    bundle.putSerializable("gdllInvbalDetail", invbalBean);
                    intent.putExtras(bundle);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });
    }

    private void initView(){
        //mWareh = PreferenceManager.getDefaultSharedPreferences(this).getString(GdllActivity.WAREH, null);
        mWareh =getIntent().getStringExtra("Wareh");
        mItnbr = getIntent().getStringExtra("gdllLlItnbr");
        mUnmsr1 = getIntent().getStringExtra("Unmsr1");
        mUnmsr2 = getIntent().getStringExtra("Unmsr2");
        mAppnum = getIntent().getDoubleExtra("Appnum",0.00d);
        TextView unmsr1Text = (TextView)findViewById(R.id.whm_gdll_ll_invbat_unmsr1);
        unmsr1Text.setText(mUnmsr1);
        TextView unmsr2Text = (TextView)findViewById(R.id.whm_gdll_ll_invbat_unmsr2);
        LinearLayout onhand2linearLayout = (LinearLayout) findViewById(R.id.whm_gdll_ll_invbat_l5);
        if(mUnmsr2.isEmpty()){
            onhand2linearLayout.setVisibility(View.GONE);
        }else {
            unmsr2Text.setText(mUnmsr2);
        }
    }

    public class GdllLlInvbatAdapter extends BaseAdapter {
        private LayoutInflater inflater = null;
        private Double tempRisnum1 = 0.00d;
        public GdllLlInvbatAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return invbalBean.getInvbats().size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder  = new ViewHolder();
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.gravity = Gravity.CENTER_VERTICAL;
            convertView = inflater.inflate(R.layout.whm_gdll_ll_invbat_list, null);
            holder.gdll_invbat_c1 = (CheckBox) convertView.findViewById(R.id.whm_gdll_ll_invbat_list_c1);
            holder.gdll_invbat_c2 = (TextView) convertView.findViewById(R.id.whm_gdll_ll_invbat_list_c2);
            holder.gdll_invbat_c3 = (TextView) convertView.findViewById(R.id.whm_gdll_ll_invbat_list_c3);
            holder.gdll_invbat_c40 = (TextView) convertView.findViewById(R.id.whm_gdll_ll_invbat_list_c40);
            final EditText c4=(EditText) convertView.findViewById(R.id.whm_gdll_ll_invbat_list_c4);
            holder.gdll_invbat_c4 = c4;
            holder.gdll_invbat_c50 = (TextView) convertView.findViewById(R.id.whm_gdll_ll_invbat_list_c50);
            final EditText c5=(EditText) convertView.findViewById(R.id.whm_gdll_ll_invbat_list_c5);
            holder.gdll_invbat_c5 = c5;

            holder.gdll_invbat_c1.setChecked(false);
            holder.gdll_invbat_c2.setText(invbalBean.getInvbats().get(position).getFixnr());
            holder.gdll_invbat_c3.setText(invbalBean.getInvbats().get(position).getVarnr());
            holder.gdll_invbat_c40.setText(invbalBean.getInvbats().get(position).getOnhand1().toString());
            holder.gdll_invbat_c4.setText("");
            holder.gdll_invbat_c50.setText(invbalBean.getInvbats().get(position).getOnhand2().toString());
            holder.gdll_invbat_c5.setText("");
            //自动匹配库存
            double sub = new BigDecimal(Double.toString(mAppnum)).subtract(new BigDecimal(Double.toString(tempRisnum1))).doubleValue();
            if(sub>0){
                holder.gdll_invbat_c1.setChecked(true);
                if(sub>=invbalBean.getInvbats().get(position).getOnhand1()){
                    holder.gdll_invbat_c4.setText(invbalBean.getInvbats().get(position).getOnhand1().toString());
                    holder.gdll_invbat_c5.setText(invbalBean.getInvbats().get(position).getOnhand2().toString());
                    tempRisnum1=tempRisnum1+invbalBean.getInvbats().get(position).getOnhand1();
                }else {
                    double s1 = ((sub) / invbalBean.getInvbats().get(position).getOnhand1()) * invbalBean.getInvbats().get(position).getOnhand2();
                    double s2= new BigDecimal(s1).setScale(4,   BigDecimal.ROUND_HALF_UP).doubleValue();
                    holder.gdll_invbat_c4.setText(String.valueOf((sub)));
                    holder.gdll_invbat_c5.setText(String.valueOf(s2));
                    tempRisnum1=tempRisnum1+sub;
                }
            }

            if(mUnmsr2.isEmpty()){
                LinearLayout layout = (LinearLayout)convertView.findViewById(R.id.whm_gdll_ll_invbat_list_l5);
                layout.setVisibility(View.GONE);
            }
            c4.addTextChangedListener(new TextWatcher() {
                Double num = 0.00;
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (!s.toString().isEmpty()&&!mUnmsr2.isEmpty()) {
                        try {
                            num = Double.parseDouble(s.toString());
                            if (num >invbalBean.getInvbats().get(position).getOnhand1()) {
                                AppUtils.showTip(GdllLlInvbatActivity.this, "发料数量不能大于库存数量");
                                c4.setText("");
                                c5.setText("");
                            } else {
                                String risnum2 = String.format("%.4f", (num / invbalBean.getInvbats().get(position).getOnhand1()) * invbalBean.getInvbats().get(position).getOnhand2());
                                c5.setText(risnum2);
                            }
                        } catch (Exception e) {
                            AppUtils.showTip(GdllLlInvbatActivity.this, "输入值格式不正确");
                        }
                    }
                }
            });
            convertView.setTag(holder);
            return convertView;
        }

        class ViewHolder {
            CheckBox gdll_invbat_c1;
            TextView gdll_invbat_c2;
            TextView gdll_invbat_c3;
            TextView gdll_invbat_c40;
            EditText gdll_invbat_c4;
            TextView gdll_invbat_c50;
            EditText gdll_invbat_c5;
        }
    }
    class InvbalCommonBean extends BaseBean {
        private InvbalBean Result;

        public InvbalBean getResult() {
            return Result;
        }

        public void setData(InvbalBean data) {
            Result = data;
        }
    }
}

